/*
 * @LastEditors: zhanghengxin ezreal.zhang@icewhale.org
 * @LastEditTime: 2022/12/1 下午8:21
 * @FilePath: /CasaOS-UI/src/router/index.js
 * @Description:
 *
 * Copyright (c) 2022 by IceWhale, All Rights Reserved.
 */

import Vue from 'vue'
import VueRouter from 'vue-router'
import api from '@/service/api'
import store from '@/store'
import route from './route.js'

Vue.use(VueRouter)

const routes = route

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch((err) => err)
}

const needInit = async () => {
  if (store.state.needInitialization) {
    return true
  }
  try {
    let userStatusRes = await api.users.getUserStatus();
    if (userStatusRes.data.success === 200 && !userStatusRes.data.data.initialized) {
      store.commit('SET_NEED_INITIALIZATION', true)
      store.commit('SET_INIT_KEY', userStatusRes.data.data.key)
      localStorage.removeItem("access_token");
      localStorage.removeItem("refresh_token");
      return true
    } else {
      return false
    }
  } catch (error) {
    console.error(error)
    return false
  }
}

async function login () {
  // console.log("login")
  // // 使用URL对象来解析URL
  // const parsedUrl = new URL(url);
  // // 获取hash部分
  // const hash = parsedUrl.hash;
  // // 使用URLSearchParams来解析hash中的查询参数
  // const params = new URLSearchParams(hash.slice(1)); // 移除'#'字符
  // // 获取参数
  // const username = params.get('username');
  // const password = params.get('password');
  try {
    // const userRes = await api.users.login(username ? username : "671619141952354534", password ? password : "671619141952354534")
    const userRes = await api.users.login('casaos', "casaos")
    localStorage.setItem("access_token", userRes.data.data.token.access_token);
    localStorage.setItem("refresh_token", userRes.data.data.token.refresh_token);
    localStorage.setItem("expires_at", userRes.data.data.token.expires_at);
    localStorage.setItem("user", JSON.stringify(userRes.data.data.user));
    store.commit("SET_USER", userRes.data.data.user);
    store.commit("SET_ACCESS_TOKEN", userRes.data.data.token.access_token);
    store.commit("SET_REFRESH_TOKEN", userRes.data.data.token.refresh_token);

    const versionRes = await api.sys.getVersion();
    if (versionRes.data.success == 200) {
      localStorage.setItem("version", versionRes.data.data.current_version);
    }
    router.push("/");
  } catch (err) {

    console.log(err)
  }
}

let is = true

// router.beforeEach(async (to, from, next) => {

  // // if (is) { 
  // //   is = false
  // //   try {
  // //     await login()
  // //   } catch (error) {
  // //   } finally {
  // //     next('/');
  // //   }
  // // } else {
  // //   next(

  // //   );

  // // }

  // const accessToken = localStorage.getItem("access_token");
  // const version = localStorage.getItem("version");
  // const requireAuth = to.matched.some(record => record.meta.requireAuth);
  // // 判断是否需要初始化
  // let needInitRes = await needInit();

  // if (to.path !== '/welcome') {
  //   if (needInitRes) {
  //     next('/welcome');
  //   } else {
  //     if (requireAuth && !accessToken) {

  //       await login()
  //       // next('/login');
  //       next('/');
  //     } else {
  //       switch (to.path) {
  //         case "/login":
  //           if (accessToken) {
  //             next('/');
  //           }
  //           break;

  //         case "/logout":
  //           localStorage.removeItem("access_token");
  //           localStorage.removeItem("refresh_token");
  //           localStorage.removeItem("wallpaper");
  //           localStorage.removeItem("user");
  //           next('/login');

  //           // await login()
  //           // next('/');
  //           break;

  //         default:
  //           if (version == null) {
  //             localStorage.removeItem("access_token");

  //             await login()
  //             // next('/login');
  //             next('/');
  //           }
  //           break;
  //       }
  //       next();
  //     }
  //   }
  // } else {
  //   if (needInitRes) {
  //     next();
  //   } else {
  //     await login()
  //     next();
  //     // next("/login");
  //   }
  // }
// });


export default router
